package users

import (
	"../common"
	"../web"
	"fmt"
	"strings"
)

type SetUserStationObj struct {
	common.BaseHandler
}

func (self *SetUserStationObj) Prepare() {
	usrs := *common.FetchAllRowsPtr(
		`SELECT TOP 10 ROW_NUMBER() OVER(ORDER BY ID), ID, NAME, ISNULL(DEPARTMENT, ''),
            	 CASE EXPIRED WHEN 0 THEN 'N' ELSE 'Y' END 
           FROM SFC_EMPLOYEE(NOLOCK)`,
		common.ConnectString, new(common.Employee))

	curr_id := 1
	iRtnData := *common.FetchOneRowPtr(
		`SELECT COUNT(ID)
           FROM SFC_EMPLOYEE(NOLOCK)`,
		common.ConnectString, new(common.RecCount))
	recnum := iRtnData.(common.RecCount).Number
	total_id := recnum / 10
	if recnum%10 > 0 {
		total_id = total_id + 1
	}

	stations := *common.FetchAllRowsPtr(
		`SELECT STATION FROM SFC_STATION(NOLOCK)`,
		self.Usr.Conn, new(common.RecDataStr))

	self.TmplData["usrs"] = usrs
	self.TmplData["curr_page"] = curr_id
	self.TmplData["total_page"] = total_id
	self.TmplData["stations"] = stations
}

func (self *SetUserStationObj) ParameterCheck() bool {
	s_idxd := strings.TrimSpace(self.Ctx.Params["userid"])
	if s_idxd == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please input the UserID.")
		return false
	}
	if self.Usr.Username != "admin" {
		if self.Usr.Username == s_idxd {
			self.TmplData["error"] = common.GetText(self.Lang, "Can't modify yourself.")
			return false
		}
	}
	usrChk := *common.FetchOneRowPtr(
		`SELECT COUNT(ID)
           FROM SFC_EMPLOYEE(NOLOCK) WHERE ID=?`,
		common.ConnectString, new(common.RecCount), s_idxd)
	recnum := usrChk.(common.RecCount).Number
	if recnum == 0 {
		self.TmplData["error"] = common.GetText(self.Lang, "Invalid UserID.")
		return false
	}

	self.Sqlparas = append(self.Sqlparas, s_idxd)
	self.Flashparas = []interface{}{s_idxd}

	return true
}

func (self *SetUserStationObj) SqlExecute() bool {
	s_idxd := self.Sqlparas[0].(string)
	tx := common.GetSqlTransaction(self.Usr.Conn)
	_, err := tx.Exec(`DELETE FROM SFC_USERSTATION WHERE USERID=?`, s_idxd)
	if err != nil {
		common.Application.SendMail(fmt.Sprintf("Delete User [%s] Station Error: %v\n", s_idxd, err))
		err = tx.Rollback()
		if err != nil {
			common.Application.SendMail(fmt.Sprintf("Rollback Delete User [%s] Station Error: %v\n", s_idxd, err))
		}
		return false
	}
	i := 1
	for k, _ := range self.Ctx.Params {
		if k == "userid" {
			continue
		}
		_, err = tx.Exec(
			`INSERT INTO SFC_USERSTATION
			   VALUES(?, ?, ?, ?, GETDATE())`, s_idxd, i, strings.TrimSpace(k), self.Usr.Username)
		if err != nil {
			common.Application.SendMail(fmt.Sprintf("Insert User [%s] Station Error: %v\n", s_idxd, err))
			err = tx.Rollback()
			if err != nil {
				common.Application.SendMail(fmt.Sprintf("Rollback Insert User [%s] Station Error: %v\n", s_idxd, err))
			}
			return false
		}
		i = i + 1
	}
	err = tx.Commit()
	if err != nil {
		common.Application.SendMail(fmt.Sprintf("Commit User [%s] Station Error: %v\n", s_idxd, err))
		err = tx.Rollback()
		if err != nil {
			common.Application.SendMail(fmt.Sprintf("Rollback User [%s] Station Error: %v\n", s_idxd, err))
		}
		return false
	}

	return true
}

func SetUsrStationHandler(ctx *web.Context) {
	self := new(SetUserStationObj)
	self.Ctx = ctx
	self.Url = "/setusrstation"
	self.Html = "setusrstation.html"
	self.Rightlist = []string{"setusrstation"}
	self.Flashstr = "Set User %v Station finished."
	self.Do(self)
}
